import 'package:flutter_admin/api/odoo/sale_order_line_odoo_api.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_product.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/product_productunitprice/product_list.dart';
import 'package:quiver/strings.dart';
import '../../../generated/l10n.dart';

class SaleInquiryProductEdit extends StatefulWidget {
  String? inquiryId;
  SaleInquiryProductEdit({this.saleInquiryProduct, this.inquiryId});

  final SaleInquiryProduct? saleInquiryProduct;

  @override
  _SaleInquiryProductEdit createState() => _SaleInquiryProductEdit();
}

class _SaleInquiryProductEdit extends State<SaleInquiryProductEdit> {
  late SaleInquiryProduct saleInquiryProduct;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  List<SelectOptionVO> companyIdList = [];
  List<SelectOptionVO> deptIdList = [];
  List<SelectOptionVO> userIdList = [];
  List<SelectOptionVO> partnerIdList = [];
  @override
  void initState() {
    super.initState();
    this.isAdd = widget.saleInquiryProduct == null;
    this.saleInquiryProduct = widget.saleInquiryProduct ?? SaleInquiryProduct();
    this.saleInquiryProduct.inquiryId = widget.inquiryId;
    if (isAdd == true) {
      this.saleInquiryProduct.taxrate = 13;
    }
    // _loadSelectVO();
  }

  // _loadSelectVO() async {
  //   setState(() {});
  // }

  _selectProduct() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductList(),
      ),
    ).then((v) {
      if (v != null) {
        //_query();
        formKey.currentState!.save();
        saleInquiryProduct.productId = v['id'].toString();
        saleInquiryProduct.productName = v['name'] != false ? v['name'] : '';
        saleInquiryProduct.description =
            v['description'] != false ? v['description'] : '';
        saleInquiryProduct.unit = v['uom_id'] != false ? v['uom_id'][1] : '';
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 300,
            label: '产品名称',
            value: saleInquiryProduct.productName,
            onSaved: (v) {
              saleInquiryProduct.productName = v;
            },
            onTap: () => _selectProduct(),
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 300,
            label: '规格型号',
            enable: false,
            value: saleInquiryProduct.description,
            onSaved: (v) {
              saleInquiryProduct.description = v;
            },
          ),
          CryInput(
            width: 300,
            label: '单位',
            enable: false,
            value: saleInquiryProduct.unit,
            onSaved: (v) {
              saleInquiryProduct.unit = v;
            },
          ),
          CryInput(
            width: 300,
            label: '技术要求',
            value: saleInquiryProduct.technicalRequirement,
            onSaved: (v) {
              saleInquiryProduct.technicalRequirement = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '数量',
            value: saleInquiryProduct.quantity,
            onSaved: (v) {
              saleInquiryProduct.quantity = v;
            },
            onChange: (v) {
              if (v != 0) {
                saleInquiryProduct.quantity = int.parse(v);
                setState(() {});
              }
              if (saleInquiryProduct.unitPrice != 0 &&
                  saleInquiryProduct.unitPrice != null &&
                  v != 0) {
                saleInquiryProduct.taxinclusiveprice =
                    int.parse(v) * saleInquiryProduct.unitPrice!;
              }
              if (saleInquiryProduct.taxinclusiveprice != null) {
                saleInquiryProduct.notaxinclusiveprice = double.parse(
                    (saleInquiryProduct.taxinclusiveprice! /
                            (1 + saleInquiryProduct.taxrate! / 100))
                        .toStringAsFixed(2));
              }
              setState(() {});
            },
            validator: (v) {
              return v!.isEmpty
                  ? S.of(context).required
                  : v == '0'
                      ? '数量不能为0'
                      : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '单价（元）',
            value: saleInquiryProduct.unitPrice,
            onSaved: (v) {
              saleInquiryProduct.unitPrice = v;
            },
            onChange: (v) {
              if (v != 0) {
                saleInquiryProduct.unitPrice = int.parse(v);
                setState(() {});
              }
              if (saleInquiryProduct.quantity != 0 &&
                  saleInquiryProduct.quantity != null &&
                  v != 0) {
                saleInquiryProduct.taxinclusiveprice =
                    int.parse(v) * saleInquiryProduct.quantity!;
              }
              if (saleInquiryProduct.taxinclusiveprice != null) {
                saleInquiryProduct.notaxinclusiveprice = double.parse(
                    (saleInquiryProduct.taxinclusiveprice! /
                            (1 + saleInquiryProduct.taxrate! / 100))
                        .toStringAsFixed(2));
              }
              setState(() {});
            },
            validator: (v) {
              return v!.isEmpty
                  ? S.of(context).required
                  : v == '0'
                      ? '单价不能为0'
                      : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '退税率%',
            value: saleInquiryProduct.taxrate,
            onSaved: (v) {
              saleInquiryProduct.taxrate = v;
            },
            onChange: (v) {
              if (v != 0) {
                saleInquiryProduct.taxrate = int.parse(v);
              }
              if (saleInquiryProduct.taxinclusiveprice != null && v != 0) {
                saleInquiryProduct.notaxinclusiveprice = double.parse(
                    (saleInquiryProduct.taxinclusiveprice! /
                            (1 + int.parse(v) / 100))
                        .toStringAsFixed(2));
              }
              setState(() {});
            },
            validator: (v) {
              v ?? 0;
              return int.parse(v ?? "0") > 100 ? '退税率小于等于100' : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '销售单价（外币）',
            value: saleInquiryProduct.foreignprice,
            onSaved: (v) {
              saleInquiryProduct.foreignprice = v;
            },
            // validator: (v) {
            //   return v!.isEmpty
            //       ? S.of(context).required
            //       : v == '0'
            //           ? '销售单价不能为0'
            //           : null;
            // },
          ),
          CryInputNum(
            width: 300,
            enable: false,
            label: '核算含税价格（元）',
            value: saleInquiryProduct.taxinclusiveprice,
            onSaved: (v) {
              saleInquiryProduct.taxinclusiveprice = v;
            },
            // validator: (v) {
            //   return v!.isEmpty
            //       ? S.of(context).required
            //       : v == '0'
            //           ? '核算含税价格不能为0'
            //           : null;
            // },
          ),
          CryInputNum(
            width: 300,
            enable: false,
            label: '核算不含税价格（元）',
            value: saleInquiryProduct.notaxinclusiveprice,
            onSaved: (v) {
              saleInquiryProduct.notaxinclusiveprice = v;
            },
            // validator: (v) {
            //   return v!.isEmpty
            //       ? S.of(context).required
            //       : v == '0'
            //           ? '核算不含税价格不能为0'
            //           : null;
            // },
          ),
          CryInputNum(
            width: 300,
            label: '单位补税及税金附加（元）',
            value: saleInquiryProduct.taxsurcharges,
            onSaved: (v) {
              saleInquiryProduct.taxsurcharges = v;
            },
            // validator: (v) {
            //   return v!.isEmpty
            //       ? S.of(context).required
            //       : v == '0'
            //           ? '单位补税及税金附加不能为0'
            //           : null;
            // },
          ),
          CryInputNum(
            width: 300,
            label: '单项利润率%',
            value: saleInquiryProduct.singleprofitmargin,
            onSaved: (v) {
              saleInquiryProduct.singleprofitmargin = v;
            },
            validator: (v) {
              return int.parse(v ?? "0") > 100 ? '单项利润率小于等于100' : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '单项换汇成本',
            value: saleInquiryProduct.summarycost,
            onSaved: (v) {
              saleInquiryProduct.summarycost = v;
            },
            // validator: (v) {
            //   return v!.isEmpty
            //       ? S.of(context).required
            //       : v == '0'
            //           ? '单项换汇成本不能为0'
            //           : null;
            // },
          ),
          CryInput(
            label: '备注',
            value: saleInquiryProduct.comment,
            onSaved: (v) {
              saleInquiryProduct.comment = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            SaleOrderLineOdooApi.saveOrUpdate(saleInquiryProduct.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
  }
}
